Sequence_table.c功能函數的定義
1.頭文件的聲明
#include"Sequence_table.h"
2.初始化、銷毀、打印函數的定義
//初始化順序表
void SLInit(SL* ps)
{
? ? ps->a = (SLDataType*)malloc(sizeof(SLDataType) * 4);
? ? if (ps->a == NULL)
? ? {
? ? ? ? perror("malloc failed");
? ? ? ? exit(-1);
? ? ? ? //return;
? ? }
? ? ps->size = 0;
? ? ps->capacity = 4;
}
//銷毀順序表
void SLDestroy(SL* ps)
{
? ? free(ps->a);
? ? ps->a = NULL;
? ? ps->capacity = ps->size = 0;
}
//打印順序表
void SLPrint(SL* ps)
{
? ? for (int i = 0; i < ps->size; i++)
? ? {
? ? ? ? printf("%d ", ps->a[i]);
? ? }
? ? printf("\n");
}
?
3.擴容函數的定義
//擴容順序表
void SLCheckCapacity(SL* ps)
{
? ? if (ps->size == ps->capacity)
? ? {
? ? ? ? SLDataType* tmp = (SLDataType*)realloc(ps->a, ps->capacity * 2 * (sizeof(SLDataType)));
? ? ? ? if (tmp == NULL)
? ? ? ? {
? ? ? ? ? ? perror("realloc failed");
? ? ? ? ? ? exit(-1);
? ? ? ? }
? ? ? ? ps->a = tmp;
? ? ? ? ps->capacity *= 2;
? ? }
}
4.尾插尾刪函數的定義
//尾插
void SLPushBack(SL* ps, SLDataType x)
{
? ? SLCheckCapacity(ps);
? ? ps->a[ps->size] = x;
? ? ps->size++;
}
//尾刪
void SLPopBack(SL* ps)
{
? ? assert(ps->size > 0);
? ? ps->size--;
}
5.頭插頭刪函數的定義
//頭插
void SLPushFront(SL* ps, SLDataType x)
{
? ? SLCheckCapacity(ps);
? ? // 挪動數據
? ? int end = ps->size - 1;
? ? while (end >= 0)
? ? {
? ? ? ? ps->a[end + 1] = ps->a[end];
? ? ? ? --end;
? ? }
? ? ps->a[0] = x;
? ? ps->size++;
}
//頭刪
void SLPopFront(SL* ps)
{
? ? assert(ps->size > 0);
? ? for (int i = 1; i <= ps->size - 1; i++) {
? ? ? ? ps->a[i - 1] = ps->a[i];
? ? }
? ? ps->size--;
}
?
6.定位插入刪除函數的定義
// 在pos位置插入x
void SLInsert(SL* ps, int pos, SLDataType x) {
? ? SLCheckCapacity(ps);
? ? int end = ps->size - 1;
? ? for (int i = end; i >= pos-1; i--) {
? ? ? ? ps->a[i + 1] = ps->a[i];
? ? }
? ? ps->a[pos-1] = x;
? ? ps->size++;
}
// 刪除pos位置的值
void SLErase(SL* ps, int pos) {
? ? assert(ps->size > 0);
? ? for (int i = pos-1; i < ps->size - 1; i++) {
? ? ? ? ps->a[i] = ps->a[i+1];
? ? }
? ? ps->size--;
}